package com.sunny.ihealth.service;

import android.app.Service;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

/**
 * 计步监听器
 * Created by Sunny  An on 2016/6/6.
 */
public class StepCounter implements SensorEventListener {

    public interface OnStepChangedListener {
        void onStepChanged(int totalStep);
    }


    private static final String TAG = "TAG::StepListener";

    //计步器
    private SensorManager sensorManager;
    private Sensor sensor;

    private OnStepChangedListener listener;

    public StepCounter(Context context) {
        sensorManager = (SensorManager) context.getSystemService(Service.SENSOR_SERVICE);
    }

    public boolean register() {
        if (sensor == null) {
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        }
        if (sensor == null) {
            Log.e(TAG, "NOT SUPPORT  step counter sensor");
            return false;
        }

        return sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    public void unRegister() {
        if (sensor != null) {
            sensorManager.unregisterListener(this);
        }
    }

    public OnStepChangedListener getListener() {
        return listener;
    }

    public void setListener(OnStepChangedListener listener) {
        this.listener = listener;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (listener != null && event.sensor == sensor) {
            listener.onStepChanged((int) event.values[0]);
            //Log.e(TAG, "event.values[0]=" + event.values[0]);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}
